import {Directive, forwardRef, Input} from '@angular/core';
import {NG_VALIDATORS, Validator, AbstractControl, Validators} from "@angular/forms";
import {ValidatorRegexPattern} from "./validator-regex-pattern";

@Directive({
  selector: '[telephone][ngModel]',
  providers: [
    {provide: NG_VALIDATORS, useExisting: forwardRef(() => TelephoneValidator), multi: true}
  ]
})
export class TelephoneValidator implements Validator {

  validate(c: AbstractControl): { [key: string]: any } {
    if (Validators.required(c) != undefined) {
      return null;
    }

    let value = c.value.trim();
    if (!value) {
      return null;
    }
    let isValid = ValidatorRegexPattern.telephone.test(value);

    return isValid ? null : {
      telephone: {
        valid: false
      }
    };
  }
}
